package com.heima.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.UserSearchDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.service.HistorySearchService;
import com.heima.search.service.SearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.apache.lucene.queryparser.xml.builders.BooleanQueryBuilder;
import org.apache.lucene.search.BooleanQuery;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 陈辉
 * @data 2024 16:07
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private HistorySearchService historySearchService;

    /**
     * app文章搜索
     *
     * @param searchDto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto searchDto) {
        try {
            //保存用户本次的搜索记录
            historySearchService.saveHistory(searchDto.getSearchWords(), ApThreadLocalUtil.get());

            //1. 准备查询参数： query, from,size,sort,highlight
            SearchRequest request = new SearchRequest("app_info_article");
            //1.1 组装查询条件：query
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.multiMatchQuery(searchDto.getSearchWords(),"title","content"));
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(searchDto.getMinBehotTime()));
            request.source().query(boolQueryBuilder);
            //1.2 组装分页部分：from,size
            request.source().from(searchDto.getFromIndex());
            request.source().size(searchDto.getPageSize());
            //1.3 组装排序部分：sort
            request.source().sort("publishTime", SortOrder.DESC);
            //1.4 组装高亮部分：highlight
            request.source().highlighter(new HighlightBuilder()
                    .field("title")
                    .preTags("<font style='color: red; font-size: inherit;'>")
                    .postTags("</font>"));

            //2. 向ES发送查询请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

            //3. 解析ES响应的结果数据
            SearchHit[] hits = response.getHits().getHits();
            List<JSONObject> res = new ArrayList<>();

            for (SearchHit hit : hits) {
                String articleJSON = hit.getSourceAsString();
                JSONObject jsonObject = JSONObject.parseObject(articleJSON);

                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if ( highlightFields != null && highlightFields.size() > 0){
                    //处理高亮的title
                    String highlightTitle = highlightFields.get("title").getFragments()[0].string();
                    jsonObject.put("h_title",highlightTitle);
                }else{
                    //使用原始标题
                    jsonObject.put("h_title",jsonObject.get("title"));
                }
                res.add(jsonObject);
            }

            return ResponseResult.okResult(res);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
